package com.common.aspect;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import com.common.dto.base.BaseDTO;
import com.common.util.ConstantDefine;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 *分页处理切面
 */
@Aspect
public class PagingAspectService {
	private Logger logger = Logger.getLogger(this.getClass());

	public PagingAspectService(){
	}

	@Around("execution(* com.common.service.*.*Paging(..))")
	public Object processParam(ProceedingJoinPoint jp) throws Throwable {
		logger.info("开始分页");
		Object[] args = jp.getArgs();
		if(args==null || args.length <= 0){
			return jp.proceed();
		}		
		BaseDTO baseDTO = (BaseDTO) args[0];
		//分页查询
        PageHelper.startPage(baseDTO.getPage(), baseDTO.getRows());
        //调用目标对象
        Object obj = jp.proceed(args);
        List list = null;
        Map<String,Object> result = new HashMap<String, Object>() ;
        if(obj instanceof List){
        	list = (List) obj;
        }else{
        	result = (Map<String, Object>) obj;
        	//为了适应eausyui而写，其他前端框架可以删除
        	list = (List) result.get(ConstantDefine.ROWS);
        }
        PageInfo pageInfo = new PageInfo(list);
        //返回数据
		result.put(ConstantDefine.TOTAL, pageInfo.getTotal());		
		result.put(ConstantDefine.PAGINATION, pageInfo); 
		result.remove(ConstantDefine.ROWS);
		list = null;
		logger.info("查询结果："+result);
		// 以改变后的参数去执行目标方法，并保存目标方法执行后的返回值
		return result;
	}
}
